import globalCache from "../../cache.js";
import { detailSql, getResult } from "../../util/operateSql.js";

const UserTable = 'activity_master.users'
const AccountTable = 'activity_master.t_orgnization'

// 是否存在用户
function isExistUser(req, res, next) {
  const source = req.headers['x-app-sources']
  if (!source) {
    next(new Error('未携带x-app-sources'))
    return
  }
  const isPC = source.toLowerCase() === 'pc'
  const isApplet = source.toLowerCase() === 'applet'
  const {email,openid,admin,password} = req.body
  let sql = ''
  if (isPC) {
    req.sources = 'pc'
    sql = `select * from ${UserTable} where email = '${email}'`
  } else if (isApplet) {
    req.sources = 'applet'
    sql = `select * from ${AccountTable} where  openid = '${openid}'`
  }
  
  if (!sql) {
    next()
    return
  } 
  getResult(sql).then((result) => {    
    
    if (result.length > 0) {
      req.isExistUser = true
      req.userInfo = result[0]
    }
  }).finally(() => {
    next()
  })
}

// 微信用户登录状态
function hasLogin(req, res, next) {
  // if (req.headers.token) {
  //   next()
  //   return
  // }
  const token = req.headers.authorization || req.headers.token
  const hasLogin = globalCache.getCache('token', `${token}`)
  if (hasLogin) {
    req.hasLogin = true
    next()
  } else {
    req.hasLogin = false
    next(409)
  }
}
// web用户登录状态
function hasWebLogin(req, res, next) {
  const token = req.headers.authorization
  const hasLogin = globalCache.getCache('token', `${token}`)
  
  if (hasLogin) {
    req.hasLogin = true
    req.account = hasLogin
  }
  else {
    req.hasLogin = false
  }
  next()
}

// 密码验证
function veriPassword(req, res, next) {
  const body = req.body
  const sql = `select count(*) as count from ${UserTable} where email = '${body.email}' and password = '${body.password}'`
  getResult(sql).then((result) => {
    if (result[0].count > 0) {
      req.veriPassword = true
    } else {
      req.veriPassword = false
    }
  }).finally(() => {
    next()
  })
}

/**
 * 获取用户信息
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 * return req.master登录状态返回用户信息
 */
export const getAccount = async (req,res,next) => {
  const token = req.headers.authorization || req.headers.token
  const user = globalCache.getCache('token',token)
	const isManage = user.is_manage || 0
  const openid = user?.openid
  const email = user?.email
  
  const getIdSql = detailSql(isManage?UserTable:AccountTable,isManage? {email}: {openid})
	
  
  const detail = await getResult(getIdSql)  
  if (!detail ) throw new Error('unknow Error')

  if (detail.length>0) {
    req.master = detail[0]
  }
  next()

}

/**
 * 获取用户平台
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function getPlatform(req,res,next) {
  const platform = req.headers['x-app-sources']
  req.platform = platform.toLowerCase()
  next()
}



export {
  hasLogin,
  hasWebLogin, isExistUser, veriPassword,
  getPlatform
};

